/**
 * @author yxw
 * date : 2013年10月7日 下午2:04:57 
 */
package com.tzinfo.tzt.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.tzinfo.tzt.R;
import com.tzinfo.tzt.activity.view.MyPickViewPopupWindow;
import com.tzinfo.tzt.domain.SeeNote;
import com.tzinfo.tzt.service.HouseSeeNoteService;
import com.tzinfo.tzt.util.FileTools;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.Toast;

public class SeeNotesUpdateActivity extends BaseActivity implements
		OnClickListener {

	private Button backBtn, saveBtn, deleteBtn;
	private TextView titleText;
	public TextView text_time, text_date, text_direction, text_type,
			text_floor;
	private EditText et_xiaoqu_name, et_xiaoqu_address, et_price, et_size,
			et_remark, et_agent_name, et_agent_tel;
	private LinearLayout dataLayout, timeLayout, directionLayout, typeLayout,
			floorLayout;

	private LinearLayout imagesLayout = null;
	private MyPickViewPopupWindow pickMenuWindow;
	private SeeNote seeNote = null;
	private String temp_seeNote = null;
	private HouseSeeNoteService seeNoteService;
	Builder dialog;
	private List<String> delPathList=new ArrayList<String>();
	protected SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");// 设置日期格式
	protected SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_see_notes_update);
		Intent thisIntent = this.getIntent();
		seeNote = (SeeNote) thisIntent.getSerializableExtra("seeNote");
		// 克隆 用于判断是否有数据进行修改
		if (seeNote != null) {
			temp_seeNote = seeNote.toString();
		}
		seeNoteService = new HouseSeeNoteService(this);
		init();
	}

	private void init() {
		// 图片删除
		imagesLayout = (LinearLayout) this
				.findViewById(R.id.layout_images_delete);

		saveBtn = (Button) this.findViewById(R.id.bt_save);
		saveBtn.setOnClickListener(this);
		backBtn = (Button) this.findViewById(R.id.bt_back);
		backBtn.setOnClickListener(this);
		deleteBtn = (Button) this.findViewById(R.id.bt_delete);
		deleteBtn.setOnClickListener(this);

		text_time = (TextView) this.findViewById(R.id.text_time);
		text_date = (TextView) this.findViewById(R.id.text_date);
		text_direction = (TextView) this.findViewById(R.id.text_direction);
		text_type = (TextView) this.findViewById(R.id.text_type);
		text_floor = (TextView) this.findViewById(R.id.text_floor);

		titleText = (TextView) this.findViewById(R.id.text_title);
		if (seeNote == null) {
			titleText.setText("添加看房单");
			deleteBtn.setVisibility(View.GONE);
		}

		et_xiaoqu_name = (EditText) this.findViewById(R.id.et_xiaoqu_name);
		et_xiaoqu_address = (EditText) this
				.findViewById(R.id.et_xiaoqu_address);
		et_price = (EditText) this.findViewById(R.id.et_price);
		et_size = (EditText) this.findViewById(R.id.et_size2);
		et_remark = (EditText) this.findViewById(R.id.et_remark);
		et_agent_name = (EditText) this.findViewById(R.id.et_agent_name);
		et_agent_tel = (EditText) this.findViewById(R.id.et_agent_tel);

		dataLayout = (LinearLayout) this.findViewById(R.id.layout_date);
		dataLayout.setOnClickListener(this);
		timeLayout = (LinearLayout) this.findViewById(R.id.layout_time);
		timeLayout.setOnClickListener(this);
		directionLayout = (LinearLayout) this
				.findViewById(R.id.layout_direction);
		directionLayout.setOnClickListener(this);
		typeLayout = (LinearLayout) this.findViewById(R.id.layout_type);
		typeLayout.setOnClickListener(this);
		floorLayout = (LinearLayout) this.findViewById(R.id.layout_floor);
		floorLayout.setOnClickListener(this);

		if (seeNote != null) {
			setData();
			new Thread(imageLoadRun).start();
		}

		dialog = new Builder(SeeNotesUpdateActivity.this)
				.setTitle(getResources().getString(R.string.tips))
				.setMessage("是否放弃编辑")
				.setPositiveButton("继续编辑",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
							}
						})
				.setNegativeButton("放	弃",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								finish();
							}
						});

	}

	private void setData() {
		text_date.setText(seeNote.getDate());
		text_time.setText(seeNote.getTime());
		text_direction.setText(seeNote.getDirection());
		text_type.setText(seeNote.getType());
		text_floor.setText(seeNote.getFloor());
		et_xiaoqu_name.setText(seeNote.getVillageName());
		et_xiaoqu_address.setText(seeNote.getVillageAddress());
		et_size.setText(seeNote.getSize() + "");
		et_price.setText(seeNote.getPrice());
		et_remark.setText(seeNote.getRemark());
		et_agent_name.setText(seeNote.getAgentName());
		et_agent_tel.setText(seeNote.getAgentTel());
	}

	private void getSeeNote() {
		if (seeNote == null) {
			seeNote = new SeeNote();
		}
		seeNote.setDate(text_date.getText().toString());
		seeNote.setTime(text_time.getText().toString());
		seeNote.setDirection(text_direction.getText().toString());
		seeNote.setType(text_type.getText().toString());
		seeNote.setFloor(text_floor.getText().toString());
		seeNote.setVillageName(et_xiaoqu_name.getText().toString());
		seeNote.setVillageAddress(et_xiaoqu_address.getText().toString());
		if (!"".equals(et_size.getText().toString()))
			seeNote.setSize(Integer.parseInt(et_size.getText().toString()));
		seeNote.setPrice(et_price.getText().toString());
		seeNote.setRemark(et_remark.getText().toString());
		seeNote.setAgentName(et_agent_name.getText().toString());
		seeNote.setAgentTel(et_agent_tel.getText().toString());
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.bt_back:
			if (getIsChanged()) {
				dialog.show();
			} else {
				this.finish();
			}
			break;
		case R.id.bt_save:
			getSeeNote();
			seeNoteService.saveSeeNote(seeNote);
			seeNoteService.deleteImageOnSD(delPathList);
			Intent intent1 = new Intent();
			intent1.putExtra("seeNote", seeNote);
			setResult(1, intent1);
			this.finish();
			break;
		case R.id.bt_delete:
			new Builder(SeeNotesUpdateActivity.this)
					.setTitle(getResources().getString(R.string.tips))
					.setMessage("您确定要删除该笔记吗？")
					.setPositiveButton("取	消",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
								}
							})
					.setNegativeButton("确	定",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									if (seeNote != null) {
										seeNoteService
												.deleteSeeNoteById(seeNote
														.getId() + "");
										Intent intent = new Intent();
										setResult(2, intent);
										finish();
									}
								}
							}).show();
			break;
		case R.id.layout_date:
			pickMenuWindow = new MyPickViewPopupWindow(this);
			pickMenuWindow.showDatePick();
			pickMenuWindow.showAtLocation(this.findViewById(R.id.main),
					Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
			break;
		case R.id.layout_time:
			pickMenuWindow = new MyPickViewPopupWindow(this);
			pickMenuWindow.showTimePick();
			pickMenuWindow.showAtLocation(this.findViewById(R.id.main),
					Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
			break;
		case R.id.layout_direction:
			pickMenuWindow = new MyPickViewPopupWindow(this);
			pickMenuWindow.showDirectionPick();
			pickMenuWindow.showAtLocation(this.findViewById(R.id.main),
					Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
			break;
		case R.id.layout_floor:
			pickMenuWindow = new MyPickViewPopupWindow(this);
			pickMenuWindow.showFloorPick();
			pickMenuWindow.showAtLocation(this.findViewById(R.id.main),
					Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
			break;
		case R.id.layout_type:
			pickMenuWindow = new MyPickViewPopupWindow(this);
			pickMenuWindow.showTypePick();
			pickMenuWindow.showAtLocation(this.findViewById(R.id.main),
					Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
			break;
		default:
			break;
		}
	}

	private void addImagelayout(Bitmap bm, String path) {
		LayoutParams lp1 = new LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
		LinearLayout images = (LinearLayout) getLayoutInflater().inflate(
				R.layout.layout_seenoteupdate_image, null);
		TextView timeText = (TextView) images.findViewById(R.id.time);
		String[] times = path.split("_");
		if (times.length > 1) {
			String[] timess = times[times.length - 1].split(" ");
			timeText.setText(timess[0] + " " + timess[1].replaceAll("-", ":"));
		} else {
			timeText.setText(df.format(new Date()));
		}
		ImageView imageView = (ImageView) images.findViewById(R.id.image);
		imageView.setImageBitmap(bm);
		ImageView deleteView = (ImageView) images
				.findViewById(R.id.delete_icon);
		deleteView.setOnClickListener(new MyUpdateOnClickListener(path,images));
		imageView.setImageBitmap(bm);
		imagesLayout.addView(images, lp1);
	}

	class MyUpdateOnClickListener implements OnClickListener {

		String path;
		LinearLayout images;

		public MyUpdateOnClickListener(String path,LinearLayout images) {
			this.path = path;
			this.images=images;
		}

		@Override
		public void onClick(View arg0) {
			new Builder(SeeNotesUpdateActivity.this)
					.setTitle(getResources().getString(R.string.tips))
					.setMessage("您确定要删除这张照片吗？")
					.setPositiveButton("确	定",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									seeNote.deleteImageByPath(path);
									delPathList.add(path);
									imagesLayout.removeView(images);
									Toast.makeText(SeeNotesUpdateActivity.this,
											"已删除图片！", 3000).show();
								}
							})
					.setNegativeButton("取	消",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
								}
							}).show();
		}
	}

	private boolean getIsChanged() {
		getSeeNote();
		boolean isChanged = false;
		if (seeNote == null) {
		} else if (seeNote != null && temp_seeNote == null) {
			isChanged = true;
		} else if (!(seeNote.toString().equals(temp_seeNote))) {
			isChanged = true;
		}
		return isChanged;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (getIsChanged() && event.getKeyCode() == KeyEvent.KEYCODE_BACK
				&& event.getRepeatCount() == 0) {
			dialog.show();
			return false;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

	// 用线程加载图片 防止点击后卡机
	Runnable imageLoadRun = new Runnable() {
		@Override
		public void run() {
			List<String> images = seeNote.getImages();
			for (int i = 0; images != null && i < images.size(); i++) {
				Message msg = handler.obtainMessage();
				Bitmap bitmap = BitmapFactory.decodeFile(images.get(i));
				BitmapFactory.Options option = new BitmapFactory.Options();
				option.inSampleSize = FileTools.getInSampleSize(bitmap, 90);
				bitmap = BitmapFactory.decodeFile(images.get(i), option);
				msg.arg1 = 1;
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("bitmap", bitmap);
				map.put("path", images.get(i));

				msg.obj = map;
				handler.sendMessage(msg);
			}

		}
	};

	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.arg1) {
			case -1:
				break;
			case 1:
				Map<String, Object> map = (Map<String, Object>) msg.obj;
				addImagelayout((Bitmap) map.get("bitmap"),
						(String) map.get("path"));
				break;
			}
		}
	};

}
